import { Middleware, IMiddleware, Logger } from '@midwayjs/core';
import { JwtService } from '@midwayjs/jwt';
import { NextFunction, Context } from '@midwayjs/koa';
import { ILogger } from '@midwayjs/logger';

@Middleware()
export class JwtMiddleware implements IMiddleware<Context, NextFunction> {
  @Logger()
  logger: ILogger;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // 登录接口和公开接口不需要验证 token
      if (ctx.path === '/api/login' || ctx.path === '/api/register' || ctx.path.startsWith('/public')) {
        this.logger.info(`[JwtMiddleware] 跳过认证: ${ctx.path}`);
        return await next();
      }

      const jwtService = await ctx.requestContext.getAsync(JwtService);
      
      // 从请求头获取 token
      const token = ctx.get('Authorization')?.replace('Bearer ', '');
      
      if (!token) {
        this.logger.warn('[JwtMiddleware] 未提供认证令牌');
        ctx.status = 401;
        ctx.body = {
          code: 401,
          message: '未提供认证令牌'
        };
        return;
      }

      try {
        // 验证 token
        const decoded = await jwtService.verify(token);
        // 将用户信息保存到上下文中
        ctx.state.user = decoded;
        this.logger.info(`[JwtMiddleware] 令牌验证成功: 用户ID ${decoded.id}`);
        await next();
      } catch (err) {
        this.logger.warn('[JwtMiddleware] 令牌无效或已过期', err);
        ctx.status = 401;
        ctx.body = {
          code: 401,
          message: '令牌无效或已过期'
        };
        return;
      }
    };
  }

  static getName(): string {
    return 'jwt';
  }
}